package com.roamer.school.web.controller;

import com.roamer.school.common.conf.RedisService;
import com.roamer.school.web.util.VerifyCodeUtils;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * 验证码
 */
@RestController
public class VarifyCodeController {

    @Resource
    private RedisService redisService;

    @ApiOperation(value = "captcha", notes = "获取验证码图片")
    @GetMapping(value = "/captcha", consumes = MediaType.APPLICATION_FORM_URLENCODED_VALUE)
    public String getIdentifyCode(@RequestParam String uuid) {
        Assert.hasText(uuid, "uuid is null");
        String base64Code = null;
        try {
            String varifyCode = VerifyCodeUtils.getStringRandom(4);
            boolean result = redisService.set(uuid, varifyCode, 300L);
            Assert.isTrue(result, "redis connection fails,please check");
            base64Code = VerifyCodeUtils.imageToBase64(120, 40, varifyCode);
        } catch (IOException e) {
            e.getMessage();
        }
        return base64Code;
    }


    @ApiOperation(value = "checkVarifyCode", notes = "验证验证码")
    @RequestMapping(value = "/sys_login", method = RequestMethod.POST)
    @ResponseBody
    public String checkVarifyCode(String uuid) {
        Assert.hasText(uuid, "uuid is null");
        String base64Code = null;
        Object result = redisService.get(uuid);
        if (result != null && result != "") {
            return "200";
        } else {
            return "201";
        }


    }
}
